package com.zmc.coupon.config;

import com.lmax.disruptor.*;
import com.lmax.disruptor.dsl.ProducerType;
import com.zmc.coupon.exception.CouponHistoryUpdateExceptionHandler;
import com.zmc.coupon.infrastructure.bean.vo.CouponHistoryUpdateProducer;
import com.zmc.coupon.listener.CouponHistoryUpdateConsumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author：zmc
 * @Date：2024/12/29 12:28
 */

@Configuration
public class CouponHistoryUpdateConfig {

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;


    @Bean("couponHistoryUpdateRingBuffer")
    public RingBuffer<CouponHistoryUpdateProducer> couponHistoryUpdateRingBuffer() {
        //构建RingBuffer
        RingBuffer<CouponHistoryUpdateProducer> ringBuffer =
                RingBuffer.create(ProducerType.SINGLE,
                        new EventFactory<CouponHistoryUpdateProducer>() {
                            @Override
                            public CouponHistoryUpdateProducer newInstance() {
                                return new CouponHistoryUpdateProducer();
                            }
                        },
                        128 * 64,
                        new YieldingWaitStrategy());

        //通过ringBuffer 创建一个屏障
        SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();
        //4 构建多消费者工作池
        WorkerPool<CouponHistoryUpdateProducer> workerPool = new WorkerPool<CouponHistoryUpdateProducer>(
                ringBuffer,
                sequenceBarrier,
                new CouponHistoryUpdateExceptionHandler(),
                new CouponHistoryUpdateConsumer());
        //设置消费者的sequence序号
        ringBuffer.addGatingSequences(workerPool.getWorkerSequences());
        //启动ringBuffer
        workerPool.start(threadPoolExecutor);
        return ringBuffer;
    }
}
